from PySide6.QtWidgets import QWidget, QPushButton, QGridLayout, QLineEdit, QSizePolicy
from PySide6.QtCore import Qt
from PySide6.QtGui import QCursor

class SoftKeyboard(QWidget):
    def __init__(self, target_lineedit=None, parent=None):
        super().__init__(parent)
        self.target_lineedit = target_lineedit
        self.setWindowTitle("软键盘输入界面")
        self.setFixedSize(1024, 600)
        self.setStyleSheet("background: #f8f8f8;")
        self.init_ui()

    def init_ui(self):
        from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout
        main_layout = QVBoxLayout(self)
        # 顶部输入框
        self.input_edit = QLineEdit()
        self.input_edit.setStyleSheet("font-size: 32px; padding: 10px; background: #fff; border-radius: 8px;")
        self.input_edit.setFixedHeight(60)
        main_layout.addWidget(self.input_edit)

        # 键盘区
        keys = [
            list("qwertyuiop"),
            list("asdfghjkl"),
            list("zxcvbnm+-."),
            ["0","1","2","3","4","5","6","7","8","9"],
            ["空格", "退格"]
        ]
        grid = QGridLayout()
        for row, key_row in enumerate(keys):
            for col, key in enumerate(key_row):
                btn = QPushButton(key)
                btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
                btn.setMinimumHeight(40)
                btn.setStyleSheet("font-size: 28px;")
                # clicked may or may not pass a 'checked' argument depending on button type;
                # accept any args to avoid TypeError when signal signature varies.
                btn.clicked.connect(lambda *args, k=key: self.key_pressed(k))
                grid.addWidget(btn, row, col)
        main_layout.addLayout(grid)

        # 底部按钮区
        btn_layout = QHBoxLayout()
        finish_btn = QPushButton("完成")
        finish_btn.setStyleSheet("font-size: 28px; background: #4caf50; color: #fff; border-radius: 10px; padding: 10px 40px;")
        finish_btn.setFixedHeight(50)
        finish_btn.clicked.connect(self.finish_input)
        btn_layout.addWidget(finish_btn)

        close_btn = QPushButton("关闭")
        close_btn.setStyleSheet("font-size: 28px; background: #f88; color: #fff; border-radius: 10px; padding: 10px 40px;")
        close_btn.setFixedHeight(50)
        close_btn.clicked.connect(self.cancel_input)
        btn_layout.addWidget(close_btn)

        main_layout.addLayout(btn_layout)
        self.setLayout(main_layout)

    def show_keyboard(self):
        # 全屏界面直接居中显示
        desktop = self.screen().geometry()
        x = (desktop.width() - self.width()) // 2
        y = (desktop.height() - self.height()) // 2
        self.move(x, y)
        self.show()
        self.raise_()

    def key_pressed(self, key):
        # 只操作界面上的 input_edit
        if key == "退格":
            text = self.input_edit.text()
            self.input_edit.setText(text[:-1])
        elif key == "空格":
            self.input_edit.insert(" ")
        else:
            self.input_edit.insert(key)
    def finish_input(self):
        # 将输入内容写回原输入框
        cursor = QCursor()
        cursor.setPos(0, 0)
        if self.target_lineedit:
            value = self.input_edit.text()
            if hasattr(self.target_lineedit, "setText"):
                self.target_lineedit.setText(value)
            elif hasattr(self.target_lineedit, "setPlainText"):
                self.target_lineedit.setPlainText(value)
        self.hide()
    
    def cancel_input(self):
        # 将输入内容写回原输入框
        cursor = QCursor()
        cursor.setPos(0, 0)
        self.hide()

    def set_target(self, lineedit):
        self.target_lineedit = lineedit
        # 初始化输入框内容
        if hasattr(lineedit, "text"):
            self.input_edit.setText(lineedit.text())
        elif hasattr(lineedit, "toPlainText"):
            self.input_edit.setText(lineedit.toPlainText())
